package service

import (
	"github.com/gorilla/websocket"
	"gopkg.in/fatih/set.v0"
	"log"
	"net"
	"sync"
)

//建立一个读写锁
var rwlocker sync.RWMutex

//建立一个客户端连接Node的Map
var ClientMap map[int64]*NodeService = make(map[int64]*NodeService, 0)

type NodeService struct {
	Conn *websocket.Conn
	DataQueue chan []byte
	GroupSets set.Interface
}
var DataQueue = make(chan []byte)
//发送
func (s *NodeService) Send()  {
	for  {
		select {
		//接收到消息就发送消息
		case data := <- s.DataQueue:
			var ms MessageService
			err := ms.parseJson(data)
			if err != nil {
				log.Println(err)
				return
			}
			err = ms.Send()
			if err != nil {
				log.Println(err)
				return
			}
		}
	}
}
//接受
func (s *NodeService) Receive()  {
	for  {
		_, data, err := s.Conn.ReadMessage()
		if err != nil {
			log.Println(err.Error())
			return
		}
		//s.DataQueue <- data
		DataQueue <- data
		log.Printf("recv<=%s \n",data)
	}
}

//绑定用户
func (s * NodeService) BindUser(userId int64) {
	rwlocker.Lock()
	ClientMap[userId] = s
	rwlocker.Unlock()
}

//发送消息
func (s *NodeService) SendMsg(msg []byte) error  {
	return s.Conn.WriteMessage(websocket.TextMessage, msg)
}

//udp发送消息
func  UpdSend()  {
	log.Println("upd send")
	conn, err := net.DialUDP("udp", nil, &net.UDPAddr{
		IP:   net.IPv4(172, 17, 255, 255), //接收者的ip
		Port: 3000,
	})
	if err != nil {
		log.Panic(err.Error())
		return
	}
	defer conn.Close()
	for  {
		select {
		//接收到消息就发送消息
		case data := <- DataQueue:
			_, err := conn.Write(data)
			if err != nil {
				log.Println(err.Error())
			}
		}
	}
}
//udp接受消息
func  UpdReceive()  {
	log.Println("listen upd")
	conn, err := net.ListenUDP("udp", &net.UDPAddr{
		IP:   net.IPv4(172, 17, 255, 255),
		Port: 3000,
	})
	if err != nil {
		log.Println(err.Error())
		return
	}
	defer conn.Close()
	for  {
		var buf [512]byte
		n, err := conn.Read(buf[0:])
		if err != nil {
			log.Println(err.Error())
			return
		}
		var ms MessageService
		err = ms.parseJson(buf[0:n])
		if err != nil {
			log.Println(err)
			return
		}
		err = ms.Send()
		if err != nil {
			log.Println(err)
			return
		}
	}
	log.Println("listen end")
}

//创建node节点
func NewNode(conn *websocket.Conn) NodeService  {
	return NodeService{
		Conn:      conn,
		DataQueue: make(chan []byte, 50),
		GroupSets: set.New(set.ThreadSafe),
	}
}

